package com.xyy.ec.pop.erp.hx.utils.hx;


import com.alibaba.fastjson.JSON;
import com.xyy.ec.pop.erp.hx.config.HXTaskConfig;
import com.xyy.ec.pop.erp.hx.utils.http.RedirectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public class SeaflyApi {
    /**
     * 配置信息
     */
    @Autowired
    private HXTaskConfig comentCfg;

    /*hpppt post请求方式*/
    public <K> K doPost(String httpUrl, Map<String, Object> paramMap, Class<K> cl, SfApiConfig sfApiConfig) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        K result = null;
        String param = "";
        try {
            URL url = new URL(sfApiConfig.getDomainAddress() + httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);
            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的

            String sign = JsonUtils.objectToJson(paramMap);
            String desStr = getDesStr(sfApiConfig.getAppKey(), sign);

            param = param + "sign=" + desStr + "&";
            param = param + "appid=" + sfApiConfig.getAppId();

            os.write(param.getBytes("UTF-8"));
            os.flush();
            connection.connect();
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = JsonUtils.jsonToPojo(sbf.toString(), cl);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            if (connection != null) {
                connection.disconnect();
            }
            if (comentCfg.getIsOutPutBizLog()) {
                log.info("doPost httpUrl:{}, originParam:{}, param:{}, result:{}", connection != null ? connection.getURL() : httpUrl, JSON.toJSONString(paramMap), param, JsonUtils.objectToJson(result));
            }

        }
        return result;
    }

    /*hpppt post请求方式*/
    public static <K> K doPost1(String httpUrl, Map<String, Object> paramMap, Class<K> cl, SfApiConfig sfApiConfig) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        K result = null;
        String param = "";
        try {
            URL url = new URL(sfApiConfig.getDomainAddress() + httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的

            String sign = JsonUtils.objectToJson(paramMap);
            String desStr = getDesStr(sfApiConfig.getAppKey(), sign);

            param = param + "sign=" + desStr + "&";
            param = param + "appid=" + sfApiConfig.getAppId();

            os.write(param.getBytes("UTF-8"));
            connection.connect();
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = JsonUtils.jsonToPojo(sbf.toString(), cl);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            if (connection != null) {
                connection.disconnect();
            }
        }
//        if (comentCfg.getIsOutPutBizLog()) {
//            log.info("doPost1 httpUrl:{}, originParam:{}, param:{}, result:{}", connection != null ? connection.getURL() : httpUrl, JSON.toJSONString(paramMap), param, JsonUtils.objectToJson(result));
//        }
        return result;
    }

    public <K> K doPost(String httpUrl, Map<String, Object> paramMap, List<Map<String, Object>> data, Class<K> cl, SfApiConfig sfApiConfig) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        K result = null;
        String param = null;
        try {
            URL url = new URL(sfApiConfig.getDomainAddress() + httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的

            String sign = JsonUtils.objectToJson(paramMap);
            String desStr = getDesStr(sfApiConfig.getAppKey(), sign);

            Map mp = new HashMap();
            mp.put("sign", desStr);
            mp.put("appid", sfApiConfig.getAppId());
            mp.put("data", data);
            param = JsonUtils.objectToJson(mp);
            //log.info("海翔客户{}",param);
            os.write(param.getBytes("UTF-8"));
            connection.connect();
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = JsonUtils.jsonToPojo(sbf.toString(), cl);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            if (connection != null) {
                connection.disconnect();
            }
            if (comentCfg.getIsOutPutBizLog()) {
                log.info("doPost httpUrl:{}, originParam:{}, param:{}, result:{}", connection != null ? connection.getURL() : httpUrl, JSON.toJSONString(paramMap), param, JsonUtils.objectToJson(result));
            }
        }
        return result;
    }


    public <K> K doPostPlus(String httpUrl, Map<String, Object> paramMap, List<Map<String, Object>> data, Class<K> cl, SfApiConfig sfApiConfig) {

        K result = null;
        String sign = JsonUtils.objectToJson(paramMap);
        String desStr = getDesStr(sfApiConfig.getAppKey(), sign);

        Map mp = new HashMap();
        mp.put("sign", desStr);
        mp.put("appid", sfApiConfig.getAppId());
        mp.put("data", data);
        if (comentCfg.getImportClientsUrl().equals(httpUrl)) {
            mp.put("returnDetails", 1);
        }
        String s = RedirectUtil.doPostByJson(comentCfg.getDomainAddress() + httpUrl, JSON.toJSONString(mp));
       // log.info("海翔接口:{},入参:{},出参: {}", comentCfg.getDomainAddress() + httpUrl, JSON.toJSONString(mp), JSON.toJSONString(s));
        result = JsonUtils.jsonToPojo(s, cl);
        return result;
    }


    public <K> K doPostPlus(String httpUrl, Map<String, Object> paramMap, Map<String, Object> dataMap, Class<K> cl, SfApiConfig sfApiConfig) {
        K result = null;
        String sign = JsonUtils.objectToJson(paramMap);
        String desStr = getDesStr(sfApiConfig.getAppKey(), sign);
        Map mp = new HashMap();
        mp.put("sign", desStr);
        mp.put("appid", sfApiConfig.getAppId());
        mp.put("data", dataMap);

        String s = RedirectUtil.doPostByJson(comentCfg.getDomainAddress() + httpUrl, JSON.toJSONString(mp));
        result = JsonUtils.jsonToPojo(s, cl);
        return result;
    }


    public <K> K doPost(String httpUrl, Map<String, Object> paramMap, Map<String, Object> dataMap, Class<K> cl, SfApiConfig sfApiConfig) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        K result = null;
        String param = null;
        try {
            URL url = new URL(sfApiConfig.getDomainAddress() + httpUrl);
            // 通过远程url连接对象打开连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接请求方式
            connection.setRequestMethod("POST");
            // 设置连接主机服务器超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取主机服务器返回数据超时时间：60000毫秒
            connection.setReadTimeout(60000);

            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            connection.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的

            String sign = JsonUtils.objectToJson(paramMap);
            String desStr = getDesStr(sfApiConfig.getAppKey(), sign);
            Map mp = new HashMap();
            mp.put("sign", desStr);
            mp.put("appid", sfApiConfig.getAppId());
            mp.put("data", dataMap);
            param = JsonUtils.objectToJson(mp);
            if (comentCfg.getIsOutPutBizLog()) {
                log.info("doPost httpUrl:{}, originParam:{}, param:{}, result:{}", connection != null ? connection.getURL() : httpUrl, JSON.toJSONString(paramMap), param, JsonUtils.objectToJson(result));
            }
            os.write(param.getBytes("UTF-8"));
            connection.connect();
            // 通过连接对象获取一个输入流，向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = JsonUtils.jsonToPojo(sbf.toString(), cl);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            if (connection != null) {
                connection.disconnect();
            }

        }
        return result;
    }

    /*hpppt post请求方式*/
    public <K> K doPostPlus(String httpUrl, Map<String, Object> paramMap, Class<K> cl, SfApiConfig sfApiConfig) {
        K result = null;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        String sign = JsonUtils.objectToJson(paramMap);
        String desStr = getDesStr(sfApiConfig.getAppKey(), sign);
        Map<String, String> params = new HashMap<>();
        params.put("sign", desStr);
        params.put("appid", sfApiConfig.getAppId());
        String s = RedirectUtil.doPostByFrom(comentCfg.getDomainAddress() + httpUrl, headers, params);
        if (comentCfg.getIsOutPutBizLog()) {
            log.info("doPost httpUrl:{}, originParam:{}, param:{}, result:{}", httpUrl, JSON.toJSONString(paramMap), params, JsonUtils.objectToJson(s));
        }
        result = JsonUtils.jsonToPojo(s, cl);
        return result;
    }

    //获得加密字符串
    public static String getDesStr(String appKey, String sign) {
        try {
            DesUtils desUtils = new DesUtils(appKey);
            return desUtils.encrypt(sign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
